<template>
  <div class="cart">
    <h2>我的购物车</h2>
    
    <div v-if="cartItems.length === 0" class="empty-cart">
      <el-empty description="购物车是空的">
        <el-button type="primary" @click="$router.push('/')">去购物</el-button>
      </el-empty>
    </div>
    
    <template v-else>
      <el-table :data="cartItems" style="width: 100%">
        <el-table-column type="selection" width="55">
          <template #default="scope">
            <el-checkbox 
              :model-value="scope.row.selected === 1" 
              @change="(val) => handleSelectChange(scope.row, val ? 1 : 0)"
            />
          </template>
        </el-table-column>
        
        <el-table-column label="商品信息" min-width="400">
          <template #default="scope">
            <div class="product-info">
              <img :src="scope.row.productImage" class="product-image">
              <div class="product-details">
                <h3>{{ scope.row.productName }}</h3>
                <!-- 现在不需要这些信息，可以后期添加 -->
                <!-- <p class="group-info">
                  已团{{ scope.row.groupCount }}件 | 剩余{{ scope.row.stock }}件
                </p> -->
              </div>
            </div>
          </template>
        </el-table-column>
        
        <el-table-column label="单价" width="120">
          <template #default="scope">
            <div class="price-info">
              <span class="current-price">¥{{ scope.row.price }}</span>
              <!-- 现在不需要原价字段 -->
              <!-- <span class="original-price">¥{{ scope.row.originalPrice }}</span> -->
            </div>
          </template>
        </el-table-column>
        
        <el-table-column label="数量" width="150">
          <template #default="scope">
            <el-input-number
              v-model="scope.row.quantity"
              :min="1"
              :max="99" 
              @change="(value) => handleQuantityChange(scope.row, value)"
            />
          </template>
        </el-table-column>
        
        <el-table-column label="小计" width="120">
          <template #default="scope">
            <span class="subtotal">¥{{ calculateSubtotal(scope.row) }}</span>
          </template>
        </el-table-column>
        
        <el-table-column label="操作" width="120">
          <template #default="scope">
            <el-button
              type="danger"
              link
              @click="handleRemoveItem(scope.row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <div class="cart-footer">
        <div class="left">
          <el-checkbox :model-value="selectAll" @change="handleSelectAll">全选</el-checkbox>
          <el-button type="danger" link @click="handleBatchRemove">删除选中</el-button>
        </div>
        
        <div class="right">
          <div class="total-info">
            <span>已选择 {{ selectedCount }} 件商品</span>
            <span class="total">
              总计: <span class="price">¥{{ totalPrice.toFixed(2) }}</span>
            </span>
          </div>
          <el-button type="primary" size="large" @click="handleCheckout">
            结算
          </el-button>
        </div>
      </div>
    </template>
  </div>
</template>

<script setup>
import { ElMessage, ElMessageBox } from 'element-plus'
import { computed, ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '../stores/user'

const router = useRouter()
const userStore = useUserStore()
const cartItems = ref([])
const loading = ref(false)
const selectAll = ref(true)

// 计算小计金额
const calculateSubtotal = (item) => {
  return (item.price * item.quantity).toFixed(2)
}

// 获取认证头信息
const getAuthHeaders = () => {
  const token = localStorage.getItem('token')
  return {
    'Content-Type': 'application/json',
    'Authorization': token ? `Bearer ${token}` : ''
  }
}

// 计算选中商品数量
const selectedCount = computed(() => {
  return cartItems.value.filter(item => item.selected === 1).length
})

// 计算总价
const totalPrice = computed(() => {
  return cartItems.value
    .filter(item => item.selected === 1)
    .reduce((total, item) => total + item.price * item.quantity, 0)
})

// 获取购物车列表
const fetchCartItems = async () => {
  if (!userStore.isLoggedIn) {
    ElMessage.warning('请先登录')
    router.push('/login')
    return
  }

  try {
    loading.value = true
    
    const response = await fetch('/api/cart/items', {
      headers: getAuthHeaders()
    })
    
    if (!response.ok) {
      throw new Error('获取购物车列表失败')
    }
    
    const data = await response.json()
    
    if (data.code !== 200) {
      throw new Error(data.message || '获取购物车列表失败')
    }
    
    console.log('购物车数据:', data.data)
    cartItems.value = data.data || []
    
    // 更新全选状态
    updateSelectAllState()
    
  } catch (error) {
    console.error('获取购物车列表错误:', error)
    ElMessage.error(error.message || '获取购物车列表失败，请稍后再试')
  } finally {
    loading.value = false
  }
}

// 更新全选状态
const updateSelectAllState = () => {
  if (cartItems.value.length === 0) {
    selectAll.value = false
    return
  }
  
  selectAll.value = cartItems.value.every(item => item.selected === 1)
  console.log('全选状态:', selectAll.value)
}

// 更新购物车商品数量
const handleQuantityChange = async (item, value) => {
  try {
    const response = await fetch(`/api/cart/items/${item.id}/quantity?quantity=${value}`, {
      method: 'PUT',
      headers: getAuthHeaders()
    })
    
    if (!response.ok) {
      throw new Error('更新数量失败')
    }
    
    const data = await response.json()
    
    if (data.code !== 200) {
      throw new Error(data.message || '更新数量失败')
    }
    
    // 更新本地数据
    item.quantity = value
    
  } catch (error) {
    console.error('更新数量错误:', error)
    ElMessage.error(error.message || '更新数量失败，请稍后再试')
    // 恢复原来的数量
    fetchCartItems()
  }
}

// 更新购物车商品选中状态
const handleSelectChange = async (item, selected) => {
  try {
    const response = await fetch(`/api/cart/items/${item.id}/selected?selected=${selected}`, {
      method: 'PUT',
      headers: getAuthHeaders()
    })
    
    if (!response.ok) {
      throw new Error('更新选中状态失败')
    }
    
    const data = await response.json()
    
    if (data.code !== 200) {
      throw new Error(data.message || '更新选中状态失败')
    }
    
    // 更新本地数据
    item.selected = selected
    
    // 更新全选状态
    updateSelectAllState()
    
  } catch (error) {
    console.error('更新选中状态错误:', error)
    ElMessage.error(error.message || '更新选中状态失败，请稍后再试')
    // 恢复原来的状态
    fetchCartItems()
  }
}

// 删除购物车商品
const handleRemoveItem = (item) => {
  ElMessageBox.confirm(
    '确定要从购物车中删除该商品吗？',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(async () => {
    try {
      const response = await fetch(`/api/cart/items/${item.id}`, {
        method: 'DELETE',
        headers: getAuthHeaders()
      })
      
      if (!response.ok) {
        throw new Error('删除商品失败')
      }
      
      const data = await response.json()
      
      if (data.code !== 200) {
        throw new Error(data.message || '删除商品失败')
      }
      
      // 从本地数据中移除
      cartItems.value = cartItems.value.filter(i => i.id !== item.id)
      
      // 更新全选状态
      updateSelectAllState()
      
      ElMessage.success('删除成功')
    } catch (error) {
      console.error('删除商品错误:', error)
      ElMessage.error(error.message || '删除商品失败，请稍后再试')
    }
  }).catch(() => {})
}

// 全选/取消全选
const handleSelectAll = async (val) => {
  if (cartItems.value.length === 0) return
  
  try {
    // 如果是全选，先选中所有未选中的商品
    if (val) {
      const unselectedItems = cartItems.value.filter(item => item.selected !== 1)
      
      for (const item of unselectedItems) {
        await handleSelectChange(item, 1)
      }
    } 
    // 如果是取消全选，先取消所有已选中的商品
    else {
      const selectedItems = cartItems.value.filter(item => item.selected === 1)
      
      for (const item of selectedItems) {
        await handleSelectChange(item, 0)
      }
    }
    
    // 更新本地数据
    cartItems.value.forEach(item => {
      item.selected = val ? 1 : 0
    })
    
  } catch (error) {
    console.error('全选/取消全选错误:', error)
    ElMessage.error(error.message || '操作失败，请稍后再试')
    // 恢复原来的状态
    fetchCartItems()
  }
}

// 批量删除选中商品
const handleBatchRemove = () => {
  const selectedItems = cartItems.value.filter(item => item.selected === 1)
  if (selectedItems.length === 0) {
    ElMessage.warning('请选择要删除的商品')
    return
  }
  
  ElMessageBox.confirm(
    '确定要删除选中的商品吗？',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(async () => {
    try {
      const response = await fetch('/api/cart/items/selected', {
        method: 'DELETE',
        headers: getAuthHeaders()
      })
      
      if (!response.ok) {
        throw new Error('删除选中商品失败')
      }
      
      const data = await response.json()
      
      if (data.code !== 200) {
        throw new Error(data.message || '删除选中商品失败')
      }
      
      // 从本地数据中移除
      cartItems.value = cartItems.value.filter(item => item.selected !== 1)
      
      // 更新全选状态
      updateSelectAllState()
      
      ElMessage.success('删除成功')
    } catch (error) {
      console.error('删除选中商品错误:', error)
      ElMessage.error(error.message || '删除选中商品失败，请稍后再试')
    }
  }).catch(() => {})
}

// 结算
const handleCheckout = () => {
  const selectedItems = cartItems.value.filter(item => item.selected === 1)
  if (selectedItems.length === 0) {
    ElMessage.warning('请选择要结算的商品')
    return
  }
  
  router.push('/order/confirm')
}

// 组件挂载时获取购物车列表
onMounted(() => {
  fetchCartItems()
})
</script>

<style scoped>
.cart {
  padding: 20px;
  height: 100%;
  overflow-y: auto;
}

.empty-cart {
  margin: 40px 0;
  text-align: center;
}

.product-info {
  display: flex;
  align-items: center;
}

.product-image {
  width: 80px;
  height: 80px;
  object-fit: cover;
  margin-right: 20px;
}

.product-details h3 {
  margin: 0 0 10px 0;
  font-size: 16px;
}

.group-info {
  margin: 0;
  color: #666;
  font-size: 14px;
}

.price-info {
  display: flex;
  flex-direction: column;
}

.current-price {
  color: #f56c6c;
  font-weight: bold;
}

.original-price {
  color: #999;
  text-decoration: line-through;
  font-size: 12px;
}

.subtotal {
  color: #f56c6c;
  font-weight: bold;
}

.cart-footer {
  margin-top: 20px;
  padding: 20px;
  background-color: #f8f8f8;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.left {
  display: flex;
  align-items: center;
  gap: 20px;
}

.right {
  display: flex;
  align-items: center;
  gap: 20px;
}

.total-info {
  text-align: right;
}

.total {
  margin-left: 20px;
}

.price {
  color: #f56c6c;
  font-size: 20px;
  font-weight: bold;
}
</style> 